package fjut.acm.coding.component.judge;

import com.alibaba.fastjson.JSONObject;
import fjut.acm.coding.component.judge.data.JudgeSubmitData;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@Component
public class JudgeHttpClient {

    @Resource
    RestTemplate restTemplate;

    @Resource
    JudgeResponseExtractor judgeResponseExtractor;

    @Value("${cf.config.JudgePath}")
    private String JudgePath;

    private HttpHeaders headers = null;

    public JudgeHttpClient(){
        headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    }


    public JSONObject submit(JudgeSubmitData judgeData){
        MultiValueMap<String,Object> map = new LinkedMultiValueMap<>();
        map.add("ojid",judgeData.getOjId());
        map.add("rid",judgeData.getRid());
        map.add("pid",judgeData.getPid());
        map.add("language",judgeData.getLanguage());
        map.add("code",judgeData.getCode());
        map.add("time",judgeData.getTime());
        map.add("memory",judgeData.getMemory());

        HttpEntity<MultiValueMap<String, Object>> Request = new HttpEntity<>(map, headers);

        ResponseEntity<String> responseEntity =  doPost(JudgePath,Request);
        return judgeResponseExtractor.extractBodyAsJsonObject(responseEntity);
    }

    /**
     * 执行 post 请求，返回一个String
     */
    protected ResponseEntity<String> doPost(String url, HttpEntity<MultiValueMap<String, Object>> request) {
        return restTemplate.postForEntity(url, request, String.class);
    }
    /**
     * 执行 get 请求，返回一个String
     */
    protected ResponseEntity<String> doGet(String url, HttpEntity<MultiValueMap<String, Object>> request) {
        return restTemplate.getForEntity(url, String.class);
    }
}
